package meterMonitor.controller;
 
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat; 
import java.util.Date;
import java.util.HashMap; 
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 







import javax.servlet.http.HttpServletRequest; 

import meterMonitor.constand.APIConsts;
import meterMonitor.util.EmailBiz;
import meterMonitor.util.JacksonMapper;
import meterMonitor.util.ResourceConfig;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;  
     
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 

public class BaseController {
	public static final Logger logger = LoggerFactory.getLogger(BaseController.class);

	
	@Autowired
	protected ResourceConfig resourceConfig;
 
	
	@Autowired
	protected EmailBiz emailBiz;
	
	@Autowired
	RestTemplate restTemplate;
     
	//js版本控制
	@ModelAttribute("v")
	protected String getJsVersion() {
		return resourceConfig.getValueByKey("js.version");
	}
  

	protected String getIpAddr(HttpServletRequest request) {
		String ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
					ipAddress = inet.getHostAddress();
				} catch (UnknownHostException e) {
					logger.error("未知主机异常", e);
				}

			}
		}
		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
															// = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}

//	/**
//	 * 从request中获得参数Map，并返回可读的Map
//	 * 
//	 * @param request
//	 * @return
//	 */
//	@SuppressWarnings("unchecked")
//	protected Map<String, Object> getParameterMap(HttpServletRequest request) {
//		// 参数Map
//		Map<String, Object> properties = request.getParameterMap();
//		// 返回值Map
//		Map<String, Object> returnMap = new HashMap<String, Object>();
//		Iterator<Map.Entry<String, Object>> entries = properties.entrySet().iterator();
//		Map.Entry<String, Object> entry;
//		String name = "";
//		String value = "";
//		while (entries.hasNext()) {
//			entry = (Map.Entry<String, Object>) entries.next();
//			name = (String) entry.getKey();
//			Object valueObj = entry.getValue();
//			if (null == valueObj) {
//				value = "";
//			} else if (valueObj instanceof String[]) {
//				String[] values = (String[]) valueObj;
//				for (int i = 0; i < values.length; i++) {
//					value = StringUtils.trim(values[i]) + ",";
//				}
//				value = value.substring(0, value.length() - 1);
//			} else {
//				value = StringUtils.trim(valueObj.toString());
//			}
//			returnMap.put(name, value);
//		}
//		return returnMap;
//	}

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}

	/**
	 * 
	 * getStaticOnline(获取不同环境静态资源地址)
	 *
	 * @return
	 * @return String
	 * @exception
	 *
	 */
	@ModelAttribute("staticOnline")
	protected String getStaticOnline() {
		
		return resourceConfig.getValueByKey("staticOnline");
	}
   

	/**
	 * rest统一服务
	 * 
	 * @param uri
	 *            请求地址
	 * @param request
	 *            请求的参数实体
	 * @param method
	 *            请求的方式 get or post
	 * @param expectedStatus
	 * @return
	 */
	protected <T> ResponseEntity<String> doService(String uri, HttpEntity<T> request, HttpMethod method, HttpStatus expectedStatus) {
		ResponseEntity<String> response = null;
		try {
			logger.info("请求的地址为:" + uri);
			logger.info("请求的参数为:" + request);
			response = restTemplate.exchange(uri, method, request, String.class);
				logger.info("响应:" + response.toString());
		} catch (HttpStatusCodeException e) {
			logger.error("后台服务出错,错误异常为:" + e.getMessage(), e);
		} catch (ResourceAccessException e) {
			logger.error("连接超时," + e.getMessage(), e);
		} catch (Exception e) {
			logger.error("服务出错:" + e.getMessage(), e);
		}
		if (!uri.contains("foot")) {
			logger.info("返回信息为:" + response);
		}
		return response;
	}
	

	protected void logErrorMail(String title,Exception e)
	{		
		 this.logErrorMail(title,e,null);
	}
	

	protected void logErrorMail(String title,Exception e,String requestStr)
	{		
		try{ 
			//logger.error("异常："+title+e.getMessage(),e);
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			String strJson ="";
			try{
			strJson=IOUtils.toString(request.getInputStream(),APIConsts.ENCODING)+";"; 
			}catch(Exception ex3)
			{ 
			}
			if(requestStr!=null&&!requestStr.equals(""))
			{
			strJson+="("+requestStr+")";
			}
			Map<String, String> params = getParameterMap(request);
			strJson+="formData(map):"+JacksonMapper.toJson(params)+";"; 
		 
			//String sendStr=title+"请求："+strJson+";loginName:"+this.getLoginRealName()+";userid:"+this.getLoginId()+";";
			String sendStr="";
			//emailBiz.sendMailAsyn("异常："+title, sendStr, e);
		}
		catch(Exception ex2)
		{ 
			//logger.error("发送邮件通知及记录日志表异常："+ex2.getMessage(),ex2);
		}
	}
	protected void logBizErrorMail(String title,Exception e)
	{	
		this.logBizErrorMail(title, e, null);
	}
	protected void logBizErrorMail(String title,Exception e,String requestStr)
	{		
		try{ 
			//logger.warn("业务异常："+title+e.getMessage(),e);
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			String strJson ="";
			try{
			strJson=IOUtils.toString(request.getInputStream(),APIConsts.ENCODING)+";"; 
			}catch(Exception ex3)
			{ 
			}
			if(requestStr!=null&&!requestStr.equals(""))
			{
			strJson+="("+requestStr+")";
			}
			Map<String, String> params = getParameterMap(request);
			strJson+="formData(map):"+JacksonMapper.toJson(params)+";"; 
		 
			String sendStr=title+"请求："+strJson+";";
			emailBiz.sendMailAsyn("业务异常："+title, sendStr, e); 
		}
		catch(Exception ex2)
		{
			logger.error("发送邮件通知及记录日志表异常："+ex2.getMessage(),ex2);
		}
	}
	
	 /**
	 * 从request中获得参数Map，并返回可读的Map
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map getParameterMap(HttpServletRequest request) {
	    // 参数Map
	    Map properties = request.getParameterMap();
	    // 返回值Map
	    Map returnMap = new HashMap();
	    Iterator entries = properties.entrySet().iterator();
	    Map.Entry entry;
	    String name = "";
	    String value = "";
	    while (entries.hasNext()) {
	        entry = (Map.Entry) entries.next();
	        name = (String) entry.getKey();
	        Object valueObj = entry.getValue();
	        if(null == valueObj){
	            value = "";
	        }else if(valueObj instanceof String[]){
	            String[] values = (String[])valueObj;
	            for(int i=0;i<values.length;i++){
	                value = StringUtils.trim(values[i]) + ",";
	            }
	            value = value.substring(0, value.length()-1);
	        }else{
	            value = StringUtils.trim(valueObj.toString());
	        }
	        returnMap.put(name, value);
	    }
	    return returnMap;
	}

	private static String process(String str, Set<String> styleSet) {
		if (StringUtils.isNotBlank(str)) {
			Pattern p = Pattern.compile("<link[^>]*>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
			Matcher matcher = p.matcher(str);
			StringBuffer sbr = new StringBuffer();
			while (matcher.find()) {
				styleSet.add(removeBlank(matcher.group()));
				matcher.appendReplacement(sbr, "");
			}
			matcher.appendTail(sbr);
			return sbr.toString();
		}
		return str;
	}

	private static String removeBlank(String str) {
		if (StringUtils.isNotBlank(str)) {
			return str.replaceFirst("\\s+", " ");
		}
		return null;
	}

	private static String setToString(Set<String> set) {
		StringBuilder sbr = new StringBuilder();
		if (CollectionUtils.isNotEmpty(set)) {
			for (String string : set) {
				sbr.append(string);
			}
		}
		return sbr.toString();
	}
   
}
